<template>
  <div class="exam-take">
    <!-- 左侧答题卡 -->
    <div class="answer-card">
      <div class="card-header">答题卡</div>
      <div class="question-types">
        <!-- 单选题 -->
        <div class="question-type">
          <h4>单选题</h4>
          <div class="number-grid">
            <div
              v-for="n in 30"
              :key="'single-' + n"
              class="number-item"
              :class="getQuestionStatus(n)"
              @click="jumpToQuestion(n)"
            >
              {{ n }}
            </div>
          </div>
        </div>
        
        <!-- 多选题 -->
        <div class="question-type">
          <h4>多选题</h4>
          <div class="number-grid">
            <div
              v-for="n in 20"
              :key="'multi-' + n"
              class="number-item"
              :class="getQuestionStatus(n + 30)"
              @click="jumpToQuestion(n + 30)"
            >
              {{ n + 30 }}
            </div>
          </div>
        </div>

        <!-- 判断题 -->
        <div class="question-type">
          <h4>判断题</h4>
          <div class="number-grid">
            <div
              v-for="n in 20"
              :key="'judge-' + n"
              class="number-item"
              :class="getQuestionStatus(n + 50)"
              @click="jumpToQuestion(n + 50)"
            >
              {{ n + 50 }}
            </div>
          </div>
        </div>

        <!-- 填空题 -->
        <div class="question-type">
          <h4>填空题</h4>
          <div class="number-grid">
            <div
              v-for="n in 15"
              :key="'fill-' + n"
              class="number-item"
              :class="getQuestionStatus(n + 70)"
              @click="jumpToQuestion(n + 70)"
            >
              {{ n + 70 }}
            </div>
          </div>
        </div>

        <!-- 解答题 -->
        <div class="question-type">
          <h4>解答题</h4>
          <div class="number-grid">
            <div
              v-for="n in 15"
              :key="'answer-' + n"
              class="number-item"
              :class="getQuestionStatus(n + 85)"
              @click="jumpToQuestion(n + 85)"
            >
              {{ n + 85 }}
            </div>
          </div>
        </div>
      </div>

      <!-- 答题卡说明 -->
      <div class="card-legend">
        <div class="legend-list">
          <div class="legend-item">
            <span class="dot doing"></span>
            <span>正在作答</span>
          </div>
          <div class="legend-item">
            <span class="dot done"></span>
            <span>已作答</span>
          </div>
          <div class="legend-item">
            <span class="dot todo"></span>
            <span>待作答</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 中间答题区 -->
    <div class="question-area">
      <div class="question-content">
        <!-- 题目类型和分数 -->
        <div class="question-header">
          <div class="question-type-tag">
            <i class="question-number">{{ currentQuestion }}</i>
            {{ currentQuestionType }}（本题{{ getQuestionScore }}分）
          </div>
        </div>

        <!-- 题目内容 -->
        <div class="question-text">
          {{ currentQuestionData.content }}
        </div>

        <!-- 选项区域 -->
        <div class="options">
          <!-- 单选题 -->
          <div 
            v-if="currentQuestionType === '单选题'" 
            class="option-list"
          >
            <div
              v-for="(option, index) in currentQuestionData.options"
              :key="index"
              class="option-item"
              :class="{ active: currentAnswer === option.value }"
              @click="handleOptionClick(option.value)"
            >
              <div class="tab">{{ option.value }}</div>
              <div class="content">{{ option.label }}</div>
            </div>
          </div>

          <!-- 多选题 -->
          <div 
            v-if="currentQuestionType === '多选题'" 
            class="option-list"
          >
            <div
              v-for="(option, index) in currentQuestionData.options"
              :key="index"
              class="option-item"
              :class="{ active: currentMultiAnswer.includes(option.value) }"
              @click="handleMultiOptionClick(option.value)"
            >
              <div class="tab">{{ option.value }}</div>
              <div class="content">{{ option.label }}</div>
            </div>
          </div>

          <!-- 判断题 -->
          <div 
            v-if="currentQuestionType === '判断题'" 
            class="option-list"
          >
            <div
              v-for="option in [{ value: '正确', label: '正确' }, { value: '错误', label: '错误' }]"
              :key="option.value"
              class="option-item"
              :class="{ active: currentAnswer === option.value }"
              @click="handleOptionClick(option.value)"
            >
              <div class="content">{{ option.label }}</div>
            </div>
          </div>

          <!-- 填空题 -->
          <div 
            v-if="currentQuestionType === '填空题'" 
            class="fill-in-the-blank"
          >
            <div 
              v-for="(index) in currentQuestionData.blanks" 
              :key="index" 
              class="blank-item"
            >
              <span class="blank-label">空{{ index + 1 }}</span>
              <a-input 
                v-model="currentAnswers[index]" 
                placeholder="请输入答案" 
              />
            </div>
          </div>

          <!-- 解答题 -->
          <div 
            v-if="currentQuestionType === '解答题'" 
            class="answer-question"
          >
            <a-textarea 
              v-model:value="currentAnswerText" 
              :rows="4" 
              placeholder="请在此输入您的答案"
              class="answer-textarea"
            />
          </div>
        </div>
      </div>

      <!-- 导航按钮 -->
      <div class="navigation-buttons">
        <div class="nav-group">
          <a-button 
            v-if="currentQuestion > 1" 
            @click="prevQuestion"
          >
            上一题
          </a-button>
          <a-button 
            v-if="currentQuestion < totalQuestions" 
            type="primary" 
            @click="nextQuestion"
          >
            下一题
          </a-button>
        </div>
      </div>
    </div>

    <!-- 右侧计时区 -->
    <div class="timer-area">
      <div class="timer">
        <div class="time-display">
          {{ formatTime(remainingTime) }}
        </div>
        <div class="progress-info">
          已完成: {{ completedCount }}/{{ totalQuestions }}题
        </div>
      </div>
      <a-button type="primary" danger @click="submitExam">
        交卷
      </a-button>
    </div>

    <!-- 添加屏警告弹窗 -->
    <a-modal
      v-model:visible="switchScreenModalVisible"
      title="切屏警告"
      :closable="false"
      :maskClosable="false"
      :keyboard="false"
      @ok="handleSwitchScreenWarningOk"
    >
      <p>
        您已切屏 {{ switchScreenCount }} 次，
        还可切换 {{ maxSwitchScreenCount - switchScreenCount }} 次，
        超过 <span class="warning-text">{{ maxSwitchScreenCount }}次</span> 将
        <span class="warning-text">强行交卷</span>。
      </p>
      <template #footer>
        <a-button type="primary" @click="handleSwitchScreenWarningOk">
          我知道了
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Modal } from 'ant-design-vue'

type QuestionType = '单选题' | '多选题' | '判断题' | '填空题' | '解答题'

const router = useRouter()
const currentQuestion = ref(1)
const totalQuestions = ref(100)
const remainingTime = ref(7200) // 2小时 = 7200秒
const startTime = ref<number>(0)
let timer: number | null = null
const completedCount = ref(0)
const currentAnswer = ref('')

// 根据题目类型获取分数
const getQuestionScore = computed(() => {
  switch (currentQuestionType.value) {
    case '单选题':
      return 10
    case '多选题':
      return 15
    case '判断题':
      return 5
    case '填空题':
      return 10
    case '解答题':
      return 20
    default:
      return 0
  }
})

// 当前题目类型
const currentQuestionType = computed<QuestionType>(() => {
  const num = currentQuestion.value
  if (num <= 30) return '单选题'
  if (num <= 50) return '多选题'
  if (num <= 70) return '判断题'
  if (num <= 85) return '填空题'
  return '解答题'
})

// 多选答案数组
const currentMultiAnswer = ref<string[]>([])

// 填空题答案
const currentAnswers = ref<string[]>([])

// 解答题答案
const currentAnswerText = ref('')

// 存储答题状态的数组 (0: 未答, 1: 已答)
const questionStatus = ref<number[]>(new Array(100).fill(0))

// 当前题目数据
const currentQuestionData = computed(() => {
  if (currentQuestionType.value === '多选题') {
    return {
      content: '以下属于人工智能应用的是？（多选）',
      options: [
        { label: '人脸识别', value: 'A' },
        { label: '智能客', value: 'B' },
        { label: '自动���驶', value: 'C' },
        { label: '语音助手', value: 'D' },
        { label: '推荐系统', value: 'E' }
      ]
    }
  }
  if (currentQuestionType.value === '判断题') {
    return {
      content: '世界最大的广场是北京天安门广场吗？',
      options: []
    }
  }
  if (currentQuestionType.value === '填空题') {
    return {
      content: '我困第一部纪小说是西汉著名史学家____（1），撰号的____（2），被称为史家之绝响，无韵之____（3）。',
      blanks: [1, 2, 3] // 填空题的空白数
    }
  }
  if (currentQuestionType.value === '解答题') {
    return {
      content: '请简要说明2022年�������情控的主要措施。',
      options: [] // 解答题没有选项
    }
  }
  // ... 其他题型的数据
  return {
    content: '这是道单选题的题目内容',
    options: [
      { label: '选项A', value: 'A' },
      { label: '选项B', value: 'B' },
      { label: '选项C', value: 'C' },
      { label: '选项D', value: 'D' }
    ]
  }
})

// 获取题目状态样式
const getQuestionStatus = (questionNumber: number) => {
  if (currentQuestion.value === questionNumber) {
    return 'doing'
  } else if (questionStatus.value[questionNumber - 1] === 1) {
    return 'done'
  } else {
    return 'todo'
  }
}

// 跳转指定题目
const jumpToQuestion = (num: number) => {
  currentQuestion.value = num
}

// 上一题
const prevQuestion = () => {
  if (currentQuestion.value > 1) {
    currentQuestion.value--
  }
}

// 下一题
const nextQuestion = () => {
  if (currentQuestion.value < totalQuestions.value) {
    currentQuestion.value++
  }
}

// 格式化时间
const formatTime = (seconds: number) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 更新计时器的实现
const updateTimer = () => {
  const now = Date.now()
  const elapsed = Math.floor((now - startTime.value) / 1000)
  remainingTime.value = Math.max(7200 - elapsed, 0)

  if (remainingTime.value <= 0) {
    if (timer) {
      window.clearInterval(timer)
      timer = null
    }
    
    // 显示提示信息
    const modal = Modal.warning({
      title: '考试时间结束',
      content: '考试时间已到，系统将在 3秒后自动交卷！',
      closable: false,
      maskClosable: false,
      keyboard: false,
      footer: null // 移除底部按钮
    })

    // 3秒后自动交卷
    setTimeout(() => {
      modal.destroy() // 清除弹框
      navigateToResults()
    }, 3000)
  }
}

// 切屏相关状态
const maxSwitchScreenCount = ref(3) // 最大切屏次数
const switchScreenCount = ref(0) // 当前切屏次数
const switchScreenModalVisible = ref(false) // 警告弹窗显示状态

// 处理切屏事件
const handleVisibilityChange = () => {
  if (document.hidden) {
    switchScreenCount.value++
    
    if (switchScreenCount.value <= maxSwitchScreenCount.value) {
      // 显示警告弹窗
      switchScreenModalVisible.value = true
    }
    
    if (switchScreenCount.value > maxSwitchScreenCount.value) {
      // 超最大次数，强制交卷
      Modal.warning({
        title: '强制交卷',
        content: '您的切屏次数已超过系统限制，将自动交卷！',
        okText: '确定',
        onOk: () => {
          submitExam()
        }
      })
    }
  }
}

// 处理警告弹窗确认
const handleSwitchScreenWarningOk = () => {
  switchScreenModalVisible.value = false
  
  if (switchScreenCount.value > maxSwitchScreenCount.value) {
    submitExam()
  }
}

// 组件挂载时启动计时器
onMounted(() => {
  startTime.value = Date.now()
  timer = window.setInterval(() => {
    updateTimer()
  }, 1000)

  document.addEventListener('visibilitychange', handleVisibilityChange)
})

// 组件卸载时清理
onUnmounted(() => {
  if (timer) {
    window.clearInterval(timer)
    timer = null
  }
  document.removeEventListener('visibilitychange', handleVisibilityChange)
})

// 在切换题目时重置多选答案
watch(currentQuestion, () => {
  if (currentQuestionType.value === '多选题') {
    currentMultiAnswer.value = []
  }
})

// 添加重置答案的方法
const resetAnswer = () => {
  currentAnswer.value = ''  // 重置单选/判断题答案
  currentMultiAnswer.value = []  // 重置多选题答案
  currentAnswers.value = []  // 重置填空题答案
  currentAnswerText.value = ''  // 重置解答题答案
}

// 监听题目变化，加载已保存的答案
watch(currentQuestion, () => {
  // 这里可以添加加载已保存答案的逻辑
  // 根据 currentQuestion.value ���本地存储或��态中获取对应题目��答案
})

// 修改提交考试方法
const submitExam = async () => {
  // 如果是时间到或超过切屏次数，直接交卷
  if (remainingTime.value <= 0 || switchScreenCount.value > maxSwitchScreenCount.value) {
    navigateToResults()
    return
  }

  // 其他情况下显示确认对话框
  const unfinishedCount = checkUnfinishedCount()
  if (unfinishedCount === 0) {
    Modal.confirm({
      title: '确认交卷',
      content: '确定要提交试卷��？',
      okText: '确认提交',
      cancelText: '继续答题',
      onOk: () => {
        navigateToResults()
      }
    })
  } else {
    Modal.confirm({
      title: '确认交卷',
      content: `还有 ${unfinishedCount} 题未作答，确定要交卷吗？`,
      okText: '确认提交',
      cancelText: '继续答题',
      onOk: () => {
        navigateToResults()
      }
    })
  }
}

const checkUnfinishedCount = () => {
  // 计算未完成的题目数量
  return totalQuestions.value - completedCount.value;
};

const navigateToResults = () => {
  router.push('/score')
}

// 存储已答题的答案
const answersMap = ref(new Map())

// 保存当前题目答案
const saveAnswer = () => {
  const currentQuestionId = currentQuestion.value
  const type = currentQuestionType.value
  
  switch (type) {
    case '单选题':
    case '判断题':
      if (currentAnswer.value) {
        answersMap.value.set(currentQuestionId, currentAnswer.value)
        questionStatus.value[currentQuestionId - 1] = 1
      }
      break
    case '多选题':
      if (currentMultiAnswer.value.length > 0) {
        answersMap.value.set(currentQuestionId, [...currentMultiAnswer.value])
        questionStatus.value[currentQuestionId - 1] = 1
      }
      break
    case '填空题':
      // 检��是否���有空都有输入
      if (currentAnswers.value.some(answer => answer?.trim())) {
        answersMap.value.set(currentQuestionId, [...currentAnswers.value])
        questionStatus.value[currentQuestionId - 1] = 1
      }
      break
    case '解答题':
      // 检查解答题是否有输入内容
      if (currentAnswerText.value?.trim()) {
        answersMap.value.set(currentQuestionId, currentAnswerText.value)
        questionStatus.value[currentQuestionId - 1] = 1
      }
      break
  }
}

// 添加对填空题和解答题输入的监听
watch([currentAnswers, currentAnswerText], () => {
  saveAnswer()
}, { deep: true })

// 清空当前答案显示
const clearCurrentAnswer = () => {
  currentAnswer.value = ''
  currentMultiAnswer.value = []
}

// 加载题目答案
const loadQuestionAnswer = () => {
  const currentQuestionId = currentQuestion.value
  const savedAnswer = answersMap.value.get(currentQuestionId)
  
  // 清空当前显示的答案
  clearCurrentAnswer()
  
  // 如果该题已经答过，加载已保存的答案
  if (savedAnswer) {
    if (currentQuestionType.value === '多选题') {
      currentMultiAnswer.value = [...savedAnswer]
    } else {
      currentAnswer.value = savedAnswer
    }
  }
}

// 选项点击处理
const handleOptionClick = (value: string) => {
  currentAnswer.value = value
  saveAnswer() // 保存答案
}

// 多选题选项点击处理
const handleMultiOptionClick = (value: string) => {
  const index = currentMultiAnswer.value.indexOf(value)
  if (index === -1) {
    currentMultiAnswer.value.push(value)
  } else {
    currentMultiAnswer.value.splice(index, 1)
  }
  saveAnswer() // 保存答案
}

// 监听题目变化，加载已保存的答案
watch(currentQuestion, () => {
  loadQuestionAnswer()
})
</script>

<style lang="scss" scoped>
.exam-take {
  display: flex;
  height: 100%;
  background: #f0f2f5;
  padding: 20px 40px;
  max-width: 1600px;
  margin: 0 auto;
  overflow: hidden;
  gap: 10px;

  .answer-card {
    width: 280px;
    margin-right: 8px;
    background: #fff;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    height: 100%;

    .card-header {
      padding: 16px;
      font-size: 16px;
      font-weight: bold;
      border-bottom: 1px solid #f0f0f0;
      flex-shrink: 0;
    }

    .question-types {
      flex: 1;
      padding: 16px;
      overflow-y: auto;
      
      &::-webkit-scrollbar {
        width: 6px;
      }
      
      &::-webkit-scrollbar-thumb {
        background: #ccc;
        border-radius: 3px;
      }
      
      &::-webkit-scrollbar-track {
        background: #f0f0f0;
      }

      .question-type {
        margin-bottom: 20px;

        h4 {
          margin-bottom: 12px;
          color: #333;
        }

        .number-grid {
          display: grid;
          grid-template-columns: repeat(5, 1fr);
          gap: 8px;

          .number-item {
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 2px;
            cursor: pointer;

            &.doing { background: #faad14; color: #fff; }
            &.done { background: #52c41a; color: #fff; }
            &.todo { background: #1890ff; color: #fff; }
          }
        }
      }
    }

    .card-legend {
      padding: 12px 16px;
      background: #fafafa;
      border-top: 1px solid #f0f0f0;
      flex-shrink: 0;

      .legend-list {
        display: flex;
        justify-content: space-between;

        .legend-item {
          display: flex;
          align-items: center;

          .dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 6px;

            &.doing { background: #faad14; }
            &.done { background: #52c41a; }
            &.todo { background: #1890ff; }
          }
        }
      }
    }
  }

  .question-area {
    flex: 1;
    min-width: 0;
    margin-right: 8px;
    background: #fff;
    border-radius: 4px;
    padding: 24px;
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;

    .question-content {
      flex: 1;
      overflow-y: auto;

      .question-header {
        margin-bottom: 20px;
        
        .question-type-tag {
          display: inline-flex;
          align-items: center;
          background: #f0f7ff;
          padding: 8px 16px;
          border-radius: 4px;
          color: #1890ff;
          font-size: 16px;

          .question-number {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            background: #1890ff;
            color: #fff;
            border-radius: 50%;
            margin-right: 8px;
            font-style: normal;
            font-size: 14px;
          }
        }
      }

      .question-text {
        font-size: 16px;
        line-height: 1.6;
        color: #333;
        margin-bottom: 24px;
        padding: 0 16px;
      }

      .options {
        padding: 0 16px;

        .option-list {
          display: flex;
          flex-direction: column;
          gap: 12px;
        }

        .option-item {
          display: flex;
          align-items: center;
          width: 100%;
          border: 1px solid #d9d9d9;
          border-radius: 4px;
          cursor: pointer;
          transition: all 0.3s;
          padding: 12px 16px;

          &:hover {
            border-color: #389e0d;
          }

          &.active {
            background: #d9f7be;
            border-color: #389e0d;
            color: #389e0d;

            .tab {
              color: #389e0d;
            }
          }

          .tab {
            color: #1890ff;
            font-size: 16px;
            font-weight: 500;
            margin-right: 12px;
            transition: all 0.3s;
          }

          .content {
            flex: 1;
            line-height: 1.5;
          }
        }
      }
    }

    .navigation-buttons {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-top: 24px;
      border-top: 1px solid #f0f0f0;
      margin-top: 24px;

      .nav-group {
        display: flex;
        gap: 16px;  // 按钮之间的间距
        margin-bottom: 16px;  // 与交卷按钮的间距
      }

      .ant-btn-danger {
        min-width: 120px;  // 让交卷按钮更宽一些
      }
    }
  }

  .timer-area {
    width: 240px;
    background: #fff;
    border-radius: 4px;
    padding: 20px;
    height: fit-content;

    .timer {
      text-align: center;
      margin-bottom: 24px;

      .time-display {
        font-size: 24px;
        font-weight: bold;
        color: #1890ff;
        margin-bottom: 12px;
      }

      .progress-info {
        color: #666;
      }
    }

    .ant-btn {
      width: 100%;
    }
  }
}

// 将样式移到外层，提高优先级
:deep(.warning-text) {
  color: #ff4d4f !important;
  font-weight: bold !important;
}

// 或者使用全局样式
:global(.warning-text) {
  color: #ff4d4f !important;
  font-weight: bold !important;
}

.fill-in-the-blank {
  .blank-item {
    display: flex;
    align-items: center;
    margin-bottom: 16px;  // 输入框之间的间距

    &:last-child {
      margin-bottom: 0;  // 最后一个输入框不需要底部间距
    }

    .blank-label {
      min-width: 40px;
      margin-right: 0px;  // 标签和输入框之间的间距
      color: #666;
    }

    .ant-input {
      flex: 1;
    }
  }
}

.answer-question {
  width: 100%;
  margin-top: 16px;
  
  .answer-textarea {
    width: 100%;
    min-height: 120px;
  }
}
</style> 